using System.Web.Mvc;
using DecisionMaking.BusinessLogic;
using DecisionMaking.BusinessLogic.Model;
using MvcContrib;

namespace DecisionMaking.WebApp.Controllers
{
	[HandleError]
    [Authorize]
    public class CueAttributesController : BaseController
	{
		/// <summary>
		/// Injected by Windsor 
		/// </summary>
		public IEnvironmentManager EnvironmentManager {private get; set;}
		
		[HttpGet]
		public ActionResult List(int id)
		{
            var environment = EnvironmentManager.GetEnvironment(id);

            // make sure current user is owner of current environment
            if (!environment.Account.Equals(CurrentAccount))
            {
                return AccessDenied();
            }

			ViewData["cueAttributes"] = EnvironmentManager.GetCueAttributes(id);
			
			// pre-set the environment id for the new cue attributes form model
			return View(new CueAttributeModel{EnvironmentId = id});
		}
		
		[HttpPost]
		public ActionResult Add(CueAttributeModel model)
		{
		    if (ModelState.IsValid)
		    {
		        try 
		        {
		            EnvironmentManager.AddCueAttribute(model);
		            return this.RedirectToAction(c => c.List(model.EnvironmentId));
		        } 
		        catch (DuplicateCueAttributeNameException e) 
		        {
		            ModelState.AddModelError("Name", "A cue attribute with this name already exists");
		        }
		    }

            ViewData["cueAttributes"] = EnvironmentManager.GetCueAttributes(model.EnvironmentId);
			return View("List", model);
		}
		
		[HttpPost]
		public ActionResult Delete(int id)
		{
		    var attribute = EnvironmentManager.GetCueAttribute(id);

            // make sure current user is owner of current attribute
            if (!attribute.Environment.Account.Equals(CurrentAccount))
            {
                return AccessDenied();
            }

            EnvironmentManager.RemoveCueAttribute(id);
			
			return Json(new {success = true, deletedId = id});
		}		
	}
}

